package priv.dajie.tzzq.spider.dota.buff;

import org.apache.http.client.methods.HttpGet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import priv.dajie.tzzq.BaseStatic;
import priv.dajie.tzzq.spider.model.SpiderInfo;

import java.util.HashMap;
import java.util.Map;


public class BuffInfos extends BaseStatic {

    private static Logger logger = LogManager.getLogger(BuffInfos.class.getName());

    public static SpiderInfo getBuffInfo() {
        logger.debug("获取buff信息");
        HttpGet httpGet = new HttpGet("https://buff.163.com/market/?game=dota2");
        String html = open(httpGet);
        Document document = Jsoup.parse(html);
        Map<String, String> herosCN = getHeros(document);
        Map<String, String> raritysCN = getRaritys(document);
        Map<String, String> typesCN = getTypes(document);
        return new SpiderInfo(herosCN, raritysCN, typesCN);
    }

    private static Map<String, String> getHeros(Document document) {
        Map<String, String> heros = new HashMap<>();
        Elements lis = document.select("li[title][value^=npc]");
        for (Element li : lis)
            heros.put(li.attr("value"), li.attr("title"));
        return heros;
    }

    private static Map<String, String> getRaritys(Document document) {
        Map<String, String> raritys = new HashMap<>();
        Element div = document.select("div#search-rarity").first();
        return getStringStringMap(raritys, div);
    }

    private static Map<String, String> getTypes(Document document) {
        Map<String, String> types = new HashMap<>();
        Element div = document.select("div#search-type").first();
        getStringStringMap(types, div);
        types.remove("taunt");
        types.remove("wearable");
        types.remove("bundle");
        return types;
    }

    private static Map<String, String> getStringStringMap(Map<String, String> map, Element div) {
        Elements lis = div.select("li");
        for (Element li : lis) {
            map.put(li.attr("value"), li.attr("title"));
        }
        return map;
    }

}
